import React from 'react'
import { Input, Button, notification, Typography } from 'antd';
import userpic from './../img/newsucai/userpic.png'
import passwordpic from './../img/newsucai/passwordpic.png'
import Resetpassword from '../components/forgetPassword.js'
import store from '../untils/store.js';
import request from '../untils/request.js';

const { Link } = Typography;

class Login extends React.Component {
  // 使用类属性简化状态初始化
  store = store;
  state = {
    sysInfo: {
      name: "系统加载中...",
      status: 1,
      company_name: "系统加载中..."
    },
    formdata: { account: "", password: "" }
  };

  // 优化事件处理函数，使用箭头函数绑定this
  handlechange_normal = (key, e) => {
    const { formdata } = this.state;
    this.setState({ 
      formdata: { ...formdata, [key]: e.target.value } 
    });
  };

  checkdatavalid = (...args) => {
    const { formdata } = this.state;
    return args.every(item => {
      const value = formdata[item];
      return value !== "" && value != null && value !== undefined;
    });
  }

  // 通用提醒 - 使用解构赋值简化
  openNotification = (text) => {
    notification.open({ 
      message: '提示', 
      description: text 
    });
  };

  handlelogin = async () => {
    const { sysInfo, formdata } = this.state;
    
    // 系统维护检查
    if (sysInfo.status === 0 && formdata.account !== 10000) {
      this.openNotification(`系统维护中，请等待维护结束！预计打开时间：${sysInfo.open_time}`);
      return;
    }
    
    // 表单验证
    if (!this.checkdatavalid("account", "password")) {
      this.openNotification("检查表格是否为空");
      return;
    }
    
    try {
      // 使用async/await优化异步流程
      const data = await request("/admin/user/login", {
        method: 'POST',
        mode: 'cors',
        body: { "data": formdata }
      });
      
      if (data.code === 200) {
        this.store.getState().setuser(data);
        localStorage.setItem("user", JSON.stringify(data));
        this.openNotification(`欢迎您，${data.name}!`);
        this.props.history.push('/ship/mainpage');
      } else {
        this.openNotification(data.msg);
      }
    } catch (error) {
      this.openNotification("登录请求失败，请稍后重试");
    }
  }

  // 优化键盘事件处理
  handleKeyDown = (e) => {
    if (e.key === 'Enter') {  // 使用key而非keyCode，更符合标准
      this.handlelogin();
    }
  }

  componentDidMount() {
    // 添加键盘事件监听
    document.addEventListener('keydown', this.handleKeyDown);
    
    // 获取系统信息
    request("/admin/sys/getSysInfo", {
      mode: 'cors'
    })
    .then(data => {
      this.store.getState().setsysInfo(data);
      localStorage.setItem("sysInfo", JSON.stringify(data));
      this.setState({ sysInfo: data });
    })
    .catch(error => {
      console.error("Failed to fetch sys info:", error);
    });
  }

  componentWillUnmount() {
    // 移除事件监听，防止内存泄漏
    document.removeEventListener('keydown', this.handleKeyDown);
  }

  render() {
    const { sysInfo, formdata } = this.state;
    
    return (
      <div>
        <div style={{
          width: "100vw", 
          height: "100vh", 
          position: "absolute",
          fontSize: "2rem", 
          textAlign: "center", 
          color: "white", 
          overflow: "hidden",
          background: "linear-gradient(135deg, #14558f 0%, #1890ff 50%, #14558f 100%)",
          backgroundSize: "100% 100%",
          backgroundImage: `url(${this.store.getState().localUrl}loginBackgroundImage.png)`,
          boxShadow: "inset 0 0 100px rgba(255, 255, 255, 0.1)",
          borderTop: "1px solid rgba(255, 255, 255, 0.2)",
          borderLeft: "1px solid rgba(255, 255, 255, 0.2)",
          borderRight: "1px solid rgba(0, 0, 0, 0.2)",
          borderBottom: "1px solid rgba(0, 0, 0, 0.2)"
        }}>
          <div style={{ height: "3vh", position: "relative", top: "8vh" }} />
          <div style={{
            width: "64vw", 
            height: "64vh", 
            position: "absolute", 
            left: "18vw", 
            right: "18vw", 
            top: "18vh",
            backgroundSize: "100% 100%", 
            borderRadius: "0.5rem", 
            boxShadow: "0 0 40px rgba(0,0,0,0.7)",
            border: "2px solid #555", 
            backgroundColor: "#303030", 
            borderTop: "8px solid #1890ff"  // 主蓝色
          }}>
            <div style={{ 
              height: "51.2vh", 
              width: "25.6vw", 
              position: "absolute", 
              right: "0.8vw", 
              top: "3.2vw", 
              textAlign: "center", 
              fontSize: "0.8vw", 
              color: "white" 
            }}>
              <div style={{ 
                height: "10%", 
                width: "80%", 
                position: "relative", 
                top: "5%", 
                left: "10%", 
                margin: "0", 
                padding: "0", 
                display: "flex", 
                color: "white", 
                fontSize: "1.44vw", 
                fontWeight: "bold", 
                alignItems: "center", 
                justifyContent: "center" 
              }}>
                {sysInfo.company_name}
              </div>
              <div style={{
                height: "10%", 
                width: "80%", 
                position: "relative", 
                top: "10%", 
                left: "10%", 
                margin: "0", 
                padding: "0", 
                display: "flex",
                color: "#e6f7ff",  // 浅蓝色文本
                fontSize: "1.12vw", 
                fontWeight: "500", 
                alignItems: "center", 
                justifyContent: "center"
              }}>
                {sysInfo.name}&nbsp;{sysInfo.version}
              </div>
              
              {/* 账号输入框 */}
              <div style={{ 
                height: "5.5vh", 
                width: "80%", 
                position: "relative", 
                top: "15%", 
                left: "10%", 
                margin: "0", 
                padding: "0", 
                display: "flex", 
                alignItems: "center", 
                justifyContent: "center" 
              }}>
                <div style={{ 
                  height: "100%", 
                  width: "6.5vh", 
                  backgroundImage: `url(${userpic}) `, 
                  backgroundSize: "100% 100%", 
                  position: "absolute", 
                  top: "0", 
                  left: "0", 
                  backgroundColor: "#333", 
                  borderTopLeftRadius: "0.3rem", 
                  borderBottomLeftRadius: "0.3rem", 
                  borderLeft: "4px solid #1890ff"  // 主蓝色边框
                }}></div>
                <div style={{ 
                  height: "100%", 
                  width: "82%", 
                  position: "absolute", 
                  top: "0", 
                  right: "0", 
                  backgroundColor: "#444", 
                  borderTopRightRadius: "0.3rem", 
                  borderBottomRightRadius: "0.3rem" 
                }}>
                  <Input 
                    placeholder="请输入账号" 
                    style={{ 
                      width: "100%", 
                      height: "100%", 
                      border: "none", 
                      backgroundColor: "transparent", 
                      fontSize: "1.12vw", 
                      color: "#eee", 
                      textIndent: "2rem" 
                    }} 
                    onChange={e => this.handlechange_normal("account", e)} 
                  />
                </div>
              </div>
              
              {/* 密码输入框 */}
              <div style={{ 
                height: "5.5vh", 
                width: "80%", 
                position: "relative", 
                top: "15%", 
                left: "10%", 
                marginTop: "10%", 
                padding: "0", 
                display: "flex", 
                alignItems: "center", 
                justifyContent: "center" 
              }}>
                <div style={{ 
                  height: "100%", 
                  width: "6.5vh", 
                  backgroundImage: `url(${passwordpic}) `, 
                  backgroundSize: "100% 100%", 
                  position: "absolute", 
                  top: "0", 
                  left: "0", 
                  backgroundColor: "#333", 
                  borderTopLeftRadius: "0.3rem", 
                  borderBottomLeftRadius: "0.3rem", 
                  borderLeft: "4px solid #1890ff"  // 主蓝色边框
                }}></div>
                <div style={{ 
                  height: "100%", 
                  width: "82%", 
                  position: "absolute", 
                  top: "0", 
                  right: "0", 
                  backgroundColor: "#444", 
                  borderTopRightRadius: "0.3rem", 
                  borderBottomRightRadius: "0.3rem" 
                }}>
                  <Input 
                    type="password" 
                    placeholder="请输入密码"
                    style={{ 
                      width: "100%", 
                      height: "100%", 
                      border: "none", 
                      backgroundColor: "transparent", 
                      fontSize: "1.12vw", 
                      color: "#eee", 
                      textIndent: "2rem" 
                    }}
                    onChange={e => this.handlechange_normal("password", e)} 
                  />
                </div>
              </div>
              
              {/* 忘记密码链接 - 放在登录按钮上方右侧 */}
              <div style={{
                width: "80%",
                position: "relative",
                top: "14%",
                left: "10%",
                textAlign: "right",
                paddingRight: "0.5vw"
              }}>
                <Resetpassword username={formdata.username}>
                  <Link 
                    style={{
                      color: "#91c7ff",
                      fontSize: "0.9vw",
                      textDecoration: "underline",
                      cursor: "pointer",
                      transition: "color 0.2s"
                    }}
                    hoverStyle={{
                      color: "#e6f7ff"
                    }}
                  >
                    忘记密码?
                  </Link>
                </Resetpassword>
              </div>
              
              {/* 登录按钮 */}
              <div style={{ 
                height: "10%", 
                width: "80%", 
                position: "relative", 
                top: "15%", 
                left: "10%", 
                padding: "0", 
                display: "flex", 
                alignItems: "center", 
                justifyContent: "center" 
              }}>
                <Button 
                  type="primary" 
                  onClick={this.handlelogin}
                  style={{
                    height: "2.24vw", 
                    fontSize: "1.12vw", 
                    width: "100%", 
                    borderRadius: "0.3rem", 
                    backgroundColor: "#1890ff",  // 主蓝色按钮
                    border: "none",
                    color: "#ffffff",
                    transition: "background-color 0.2s"
                  }}
                  large
                  hoverStyle={{
                    backgroundColor: "#096dd9"
                  }}
                >
                  <strong>登录</strong>
                </Button>
              </div>
              
              {/* 系统提示信息 */}
              {sysInfo.status === 0 && (
                <div style={{
                  height: "8%",
                  width: "80%",
                  position: "relative",
                  top: "16%",
                  left: "10%",
                  padding: "0",
                  color: "#ffcccc",
                  fontSize: "0.8vw",
                  textAlign: "center",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center"
                }}>
                  系统维护中，管理员账号可正常登录
                </div>
              )}
            </div>
            
            {/* SVG图形区域 */}
            <div style={{ 
              position: "absolute", 
              left: "1.6vw", 
              top: "3.2vw", 
              width: "32vw", 
              height: "51.2vh", 
              display: "flex", 
              flexDirection: "column", 
              justifyContent: "center", 
              alignItems: "center" 
            }}>
              <svg xmlns="http://www.w3.org/2000/svg" height="240" width="240" style={{ marginTop: "1.6vh" }}>
                <g style={{ order: -1 }}>
                  <polygon
                    transform="rotate(45 120 120)"
                    strokeWidth="1.5"
                    stroke="#1890ff"  // 蓝色描边
                    fill="none"
                    points="84,84 177.6,60 156,156 60,180"
                    id="bounce1"
                  />
                  <polygon
                    transform="rotate(45 120 120)"
                    strokeWidth="1.5"
                    stroke="#1890ff"  // 蓝色描边
                    fill="none"
                    points="84,84 177.6,60 156,156 60,180"
                    id="bounce2"
                  />
                  <polygon
                    transform="rotate(45 120 120)"
                    strokeWidth="3"
                    stroke=""
                    fill="#414141"
                    points="84,84 180,60 156,156 60,180"
                  />
                  <polygon
                    strokeWidth="3"
                    stroke=""
                    fill="url(#gradiente)"
                    points="120,84 180,120 120,156 60,120"
                  />
                  <defs>
                    <linearGradient y2="100%" x2="10%" y1="0%" x1="0%" id="gradiente">
                      <stop style={{ stopColor: "#14558f", stopOpacity: 1 }} offset="20%" />
                      <stop style={{ stopColor: "#1890ff", stopOpacity: 1 }} offset="60%" />
                    </linearGradient>
                  </defs>
                  <polygon
                    transform="translate(24, 37.2)"
                    strokeWidth="3"
                    stroke=""
                    fill="#1890ff"  // 蓝色填充
                    points="96,60 96,90 96,118.8 48,90"
                  />
                  <polygon
                    transform="translate(24, 37.2)"
                    strokeWidth="3"
                    stroke=""
                    fill="url(#gradiente2)"
                    points="48,-48 96,-48 96,118.8 48,90"
                  />
                  <defs>
                    <linearGradient y2="100%" x2="0%" y1="-17%" x1="10%" id="gradiente2">
                      <stop style={{ stopColor: "#1890ff00", stopOpacity: 1 }} offset="20%" />
                      <stop
                        style={{ stopColor: "#1890ff54", stopOpacity: 1 }}
                        offset="100%"
                        id="animatedStop1"
                      />
                    </linearGradient>
                  </defs>
                  <polygon
                    transform="rotate(180 120 120) translate(24, 24)"
                    strokeWidth="3"
                    stroke=""
                    fill="#1890ff"  // 蓝色填充
                    points="96,60 96,90 96,118.8 48,90"
                  />
                  <polygon
                    transform="rotate(0 120 120) translate(72, 24)"
                    strokeWidth="3"
                    stroke=""
                    fill="url(#gradiente3)"
                    points="48,-48 96,-48 96,102 48,132.24"
                  />
                  <defs>
                    <linearGradient y2="100%" x2="10%" y1="0%" x1="0%" id="gradiente3">
                      <stop style={{ stopColor: "#1890ff00", stopOpacity: 1 }} offset="20%" />
                      <stop
                        style={{ stopColor: "#1890ff54", stopOpacity: 1 }}
                        offset="100%"
                        id="animatedStop2"
                      />
                    </linearGradient>
                  </defs>
                  <polygon
                    transform="rotate(45 120 120) translate(96, 114)"
                    strokeWidth="3"
                    stroke=""
                    fill="#7cbfff"  // 浅蓝色粒子
                    points="6,0 6,6 0,6 0,0"
                    id="particles1"
                  />
                  <polygon
                    transform="rotate(45 120 120) translate(96, 66)"
                    strokeWidth="3"
                    stroke=""
                    fill="#1890ff"  // 蓝色粒子
                    points="7.2,0 7.2,7.2 0,7.2 0,0"
                    id="particles2"
                  />
                  <polygon
                    transform="rotate(45 120 120) translate(84, 96)"
                    strokeWidth="3"
                    stroke=""
                    fill="#fff"
                    points="2.4,0 2.4,2.4 0,2.4 0,0"
                    id="particles3"
                  />
                  <polygon
                    strokeWidth="3"
                    stroke=""
                    fill="#292d34"
                    points="35.4,119.76 120,170.4 120,206.4 35.4,156"
                  />
                  <polygon
                    transform="translate(60, 110.4)"
                    strokeWidth="3"
                    stroke=""
                    fill="#1f2127"
                    points="60,60 144.6,9.6 144.6,42 60,96"
                  />
                </g>
              </svg>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Login